<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getUserProfile,
  updateUserProfile,
  updateUserPassword,
  uploadUserAvatar,
} from "@/api/index";
import { useMerchantStore } from "@/store";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";
import {
  Message,
  Phone,
  Calendar,
  Timer,
  Close,
} from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";
import { Cropper, CircleStencil } from "vue-advanced-cropper";
import "vue-advanced-cropper/dist/style.css";
import { formatImageUrl, getUserInitial } from "@/utils/image";

const router = useRouter();
const merchantStore = useMerchantStore();

// 用户信息
const userInfo = reactive({
  id: "",
  username: "",
  email: "",
  phone: "",
  avatar: "",
  role: "merchant",
  createTime: "",
  lastLoginTime: "",
});

// 用户头像首字母
const userInitials = computed(() => {
  return getUserInitial(userInfo.username) || "M";
});

// 激活的标签页
const activeTab = ref("basic");

// 基本信息表单
const basicFormRef = ref();
const basicForm = reactive({
  username: "",
  email: "",
  phone: "",
});

// 密码表单
const passwordFormRef = ref();
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 表单校验规则
const basicRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  email: [
    { required: false, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  phone: [
    { required: false, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
});

const passwordRules = reactive({
  oldPassword: [
    { required: true, message: "请输入当前密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

// 加载状态
const loading = reactive({
  profile: false,
  basic: false,
  password: false,
  avatar: false,
});

// 上传头像相关
const uploadUrl = "/api/users/avatar";
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${getToken()}`,
  };
});

// 裁剪相关
const showCropper = ref(false);
const cropperImg = ref("");
const cropperRef = ref();

// 获取用户信息
const fetchUserProfile = async () => {
  loading.profile = true;
  try {
    const res = await getUserProfile();
    const data = res.data?.data || res.data;

    console.log("获取到的用户数据:", data);

    if (data) {
      // 先处理可能的字段名差异
      if (data.createdAt && !data.createTime) {
        data.createTime = data.createdAt;
      }

      // 直接使用后端返回的头像URL，不进行任何处理
      Object.assign(userInfo, data);
      console.log("更新后的用户信息:", userInfo);

      // 初始化基本信息表单
      basicForm.username = data.username || "";
      basicForm.email = data.email || "";
      basicForm.phone = data.phone || "";
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
    ElMessage.error("获取用户信息失败，请重试");
  } finally {
    loading.profile = false;
  }
};

// 更新基本信息
const updateBasicInfo = async () => {
  if (!basicFormRef.value) return;

  await basicFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.basic = true;
      try {
        await updateUserProfile({
          username: basicForm.username,
          email: basicForm.email,
        });

        // 更新本地用户信息
        userInfo.username = basicForm.username;
        userInfo.email = basicForm.email;
        userInfo.phone = basicForm.phone; // 仅在本地更新，不发送到API

        ElMessage.success("基本信息更新成功");
      } catch (error) {
        console.error("更新基本信息失败", error);
        ElMessage.error("更新基本信息失败，请重试");
      } finally {
        loading.basic = false;
      }
    }
  });
};

// 重置基本信息表单
const resetBasicForm = () => {
  if (basicFormRef.value) {
    basicFormRef.value.resetFields();
    // 恢复为用户当前信息
    basicForm.username = userInfo.username || "";
    basicForm.email = userInfo.email || "";
    basicForm.phone = userInfo.phone || "";
  }
};

// 更新密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return;

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.password = true;
      try {
        await updateUserPassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
        });

        ElMessage.success("密码修改成功");
        // 重置密码表单
        resetPasswordForm();
      } catch (error) {
        console.error("修改密码失败", error);
        ElMessage.error("修改密码失败，请确认当前密码是否正确");
      } finally {
        loading.password = false;
      }
    }
  });
};

// 重置密码表单
const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
};

// 上传头像前的校验 + 弹出裁剪
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5; // 增加文件大小限制到5MB

  if (!isImage) {
    ElMessage.error("上传头像图片只能是图片格式!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("上传头像图片大小不能超过 5MB!");
    return false;
  }

  // 读取图片数据用于裁剪
  const reader = new FileReader();
  reader.onload = (e) => {
    cropperImg.value = e.target?.result as string;
    showCropper.value = true;
  };
  reader.readAsDataURL(file);
  // 阻止 el-upload 自动上传
  return false;
};

// 处理裁剪并上传
const handleCrop = async () => {
  if (!cropperRef.value) return;
  const result = cropperRef.value.getResult();
  if (!result || !result.canvas) {
    ElMessage.error("裁剪失败，请重试");
    return;
  }
  loading.avatar = true;
  result.canvas.toBlob(async (blob: Blob | null) => {
    if (!blob) {
      loading.avatar = false;
      return;
    }
    const formData = new FormData();
    formData.append("file", blob, "avatar.png"); // 文件名可以自定义

    try {
      const res = await uploadUserAvatar(formData);
      let url =
        typeof res.data === "string"
          ? res.data
          : res.data?.url || res.data?.data?.url || res.data?.data || res.data;
      if (typeof url === "object" && url !== null) {
        url = url.url || url.path || "";
      }
      if (typeof url !== "string" || !url) {
        ElMessage.error("头像上传失败，未获取到图片地址");
        showCropper.value = false;
        loading.avatar = false;
        return;
      }

      console.log("上传后返回的URL:", url);

      // 直接使用后端返回的URL，不进行任何处理
      userInfo.avatar = url;
      ElMessage.success("头像上传成功");

      // 更新用户资料中的头像URL
      try {
        await updateUserProfile({
          avatar: url,
        });
      } catch (error) {
        console.error("更新用户头像失败", error);
        ElMessage.warning("头像已上传，但更新用户资料失败");
      }
    } catch (e) {
      console.error("头像上传失败", e);
      ElMessage.error("头像上传失败");
    } finally {
      loading.avatar = false;
      showCropper.value = false;
    }
  }, "image/png");
};

// 取消裁剪
const handleCropCancel = () => {
  showCropper.value = false;
};

// 格式化时间
const formatDate = (dateString: string) => {
  if (!dateString) return "未知";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 处理头像加载错误
const avatarLoadError = () => {
  console.error("头像加载失败:", userInfo.avatar);
  // 使用默认头像（用户名首字母）
  userInfo.avatar = "";
};

onMounted(() => {
  fetchUserProfile();

  // 确保加载店铺信息
  if (merchantStore.stores.length === 0) {
    merchantStore.fetchStores();
  }
});
</script>

<template>
  <merchant-layout>
    <div class="profile-view">
      <h2 class="page-title">个人中心</h2>

      <el-row :gutter="20">
        <!-- 左侧个人信息卡片 -->
        <el-col :span="8">
          <el-card shadow="hover" class="profile-card">
            <div class="avatar-container">
              <el-avatar
                :size="120"
                :src="userInfo.avatar"
                @error="() => avatarLoadError()"
                crossorigin="anonymous"
              >
                {{ userInitials }}
              </el-avatar>
              <div class="upload-btn">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="() => {}"
                >
                  <el-button
                    type="primary"
                    size="small"
                    class="upload-avatar-btn"
                  >
                    更换头像
                  </el-button>
                </el-upload>
              </div>
            </div>

            <div class="user-info">
              <h3>{{ userInfo.username }}</h3>
              <p class="user-role">
                <el-tag type="warning">商家</el-tag>
              </p>
              <p class="user-email">
                <el-icon><Message /></el-icon>
                {{ userInfo.email || "未设置邮箱" }}
              </p>
              <p class="user-phone">
                <el-icon><Phone /></el-icon>
                {{ userInfo.phone || "未设置手机号" }}
              </p>
              <p class="user-register-time">
                <el-icon><Calendar /></el-icon>
                注册时间: {{ formatDate(userInfo.createTime) }}
              </p>
              <p class="user-last-login">
                <el-icon><Timer /></el-icon>
                最后登录: {{ formatDate(userInfo.lastLoginTime) }}
              </p>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧信息设置 -->
        <el-col :span="16">
          <el-card shadow="hover" class="settings-card">
            <template #header>
              <div class="card-header">
                <span>账号设置</span>
              </div>
            </template>

            <el-tabs v-model="activeTab">
              <!-- 基本信息设置 -->
              <el-tab-pane label="基本信息" name="basic">
                <el-form
                  ref="basicFormRef"
                  :model="basicForm"
                  :rules="basicRules"
                  label-width="100px"
                  class="settings-form"
                  v-loading="loading.basic"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="basicForm.username" />
                  </el-form-item>

                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="basicForm.email" />
                  </el-form-item>

                  <el-form-item label="手机号" prop="phone">
                    <el-input v-model="basicForm.phone" />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" @click="updateBasicInfo">
                      保存修改
                    </el-button>
                    <el-button @click="resetBasicForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <!-- 密码修改 -->
              <el-tab-pane label="修改密码" name="password">
                <el-form
                  ref="passwordFormRef"
                  :model="passwordForm"
                  :rules="passwordRules"
                  label-width="100px"
                  class="settings-form"
                  v-loading="loading.password"
                >
                  <el-form-item label="当前密码" prop="oldPassword">
                    <el-input
                      v-model="passwordForm.oldPassword"
                      type="password"
                      show-password
                    />
                  </el-form-item>

                  <el-form-item label="新密码" prop="newPassword">
                    <el-input
                      v-model="passwordForm.newPassword"
                      type="password"
                      show-password
                    />
                  </el-form-item>

                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      show-password
                    />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" @click="updatePassword">
                      修改密码
                    </el-button>
                    <el-button @click="resetPasswordForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>

      <!-- 裁剪弹窗 -->
      <el-dialog
        v-model="showCropper"
        title="裁剪用户头像"
        width="400px"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <template #header>
          <div class="custom-dialog-header">
            <span>裁剪用户头像</span>
            <button
              class="custom-close-btn"
              @click="showCropper = false"
              aria-label="关闭"
            >
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </template>
        <div style="display: flex; flex-direction: column; align-items: center">
          <Cropper
            ref="cropperRef"
            :src="cropperImg"
            :stencil-component="CircleStencil"
            :stencil-props="{ aspectRatio: 1 }"
            :autoZoom="true"
            :resizeImage="true"
            :imageRestriction="'stencil'"
            style="width: 300px; height: 300px; background: #f5f5f5"
          />
          <div style="margin-top: 16px">
            <el-button type="primary" @click="handleCrop">裁剪并上传</el-button>
            <el-button @click="handleCropCancel">取消</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </merchant-layout>
</template>

<style scoped>
.profile-view {
  width: 100%;
}

.page-title {
  margin-bottom: 20px;
  color: var(--primary-dark);
  font-size: 1.5rem;
}

.profile-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.upload-btn {
  margin-top: 15px;
}

.upload-avatar-btn {
  border-radius: 20px;
}

.user-info {
  width: 100%;
  text-align: center;
}

.user-info h3 {
  margin: 10px 0;
  font-size: 1.2rem;
  color: var(--text-primary);
}

.user-role {
  margin-bottom: 15px;
}

.user-email,
.user-phone,
.user-register-time,
.user-last-login {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 8px 0;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.user-email .el-icon,
.user-phone .el-icon,
.user-register-time .el-icon,
.user-last-login .el-icon {
  margin-right: 8px;
  color: var(--primary);
}

.settings-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.settings-form {
  max-width: 500px;
  margin: 20px auto;
}

/* Custom dialog header styles from StoreView.vue */
.custom-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  padding-right: 4px;
}
.custom-close-btn {
  border: none;
  background: #f5f6fa;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-left: 8px;
}
.custom-close-btn:hover {
  background: #ffd54f;
  color: #a05a1c;
  box-shadow: 0 4px 16px rgba(255, 213, 79, 0.15);
}
</style>
